package com.bilibili.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bilibili.dao.AuthRoleMapper;
import com.bilibili.dao.UserRoleMapper;
import com.bilibili.domain.constant.AuthRoleConstant;
import com.bilibili.domain.entity.*;
import com.bilibili.service.AuthRoleMenuService;
import com.bilibili.service.AuthRoleService;
import com.bilibili.service.UserAuthService;

import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * projectName:com.bilibili.service.impl
 *
 * @author 飞
 * @create by 2024/6/1022:59
 * description:
 */
@Service
public class UserAuthServiceImpl implements UserAuthService {
    @Resource
    private UserRoleMapper userRoleMapper;

    @Resource
    private AuthRoleService authRoleService;

    @Resource
    private AuthRoleMenuService authRoleMenuService;

    private LambdaQueryWrapper<UserRole> userRoleWrapper = new LambdaQueryWrapper<>();
    private LambdaQueryWrapper<AuthRole> authRoleWrapper = new LambdaQueryWrapper<>();

    @Override
    public UserAuthorities getUserAuthorities(Long userId) {
        UserAuthorities userAuthorities = new UserAuthorities();
        userRoleWrapper.eq(UserRole::getUserId,userId);
        List<UserRole> userRoles = userRoleMapper.selectList(userRoleWrapper);
        //获取权限id
        Set<Long> roleIdSet = userRoles.stream()
                .map(UserRole::getRoleId)
                .collect(Collectors.toSet());


        //角色和操作
        List<AuthRoleElementOperation> roleElementOperationList = authRoleService.getRoleElementOperationByRoleIds(roleIdSet);

        //角色和菜单
        List<AuthRoleMenu> authRoleMenuList = authRoleMenuService.getAuthRoleMenuByRoleIds(roleIdSet);
        userAuthorities.setRoleElementOperationList(roleElementOperationList);
        userAuthorities.setRoleMenuList(authRoleMenuList);
        return userAuthorities;
    }

    @Override
    public void addUserDefaultRole(Long id) {
        authRoleWrapper.eq(AuthRole::getCode, AuthRoleConstant.ROLE_LV0);
        UserRole userRole = new UserRole();
        AuthRole authRole = authRoleService.getOne(authRoleWrapper);
        userRole.setUserId(id);
        userRole.setRoleId(authRole.getId());
        userRoleMapper.insert(userRole);
    }
}
